import axiosTool from 'ys-vui/src/axiosTool'
import util from './util'

type PermissionCache = {
  [x: string]: API.PermissionItem & {
    isOrgAdmin: boolean
  }
}

const ORGADMIN_CACHE: PermissionCache = {}


export const PermissionName = {
  OfflineTrainingMenu: "MENU-CORPTRAINING",
  SurveyMenu: "MENU-CORPSURVEY",
}

/** 根据key获取权限，并缓存 */
export async function getPermission(name: string) {
  if (ORGADMIN_CACHE[name]) {
    return ORGADMIN_CACHE[name]
  }

  const result = await axiosTool.Axios.request<API.APIData<API.PermissionItem>>({
    url: `${util.basePath}/admin/common/getPermission`,
    params: {
      name,
    }
  })
  if (!result.data.status) {
    return null
  }
  const data = result.data.data
  ORGADMIN_CACHE[name] = {
    ...data,
    isOrgAdmin: data.dataRange === 0,
  }
  return ORGADMIN_CACHE[name]
}